package com.hksj.wmp.config;

import com.foxinmy.weixin4j.cache.CacheStorager;
import com.foxinmy.weixin4j.cache.Cacheable;
import com.hksj.common.config.cache.RedisCache;
import com.hksj.jetlinks.serialize.ObjectRedisSerializer;
import org.springframework.util.ObjectUtils;

import java.util.Collection;
import java.util.concurrent.TimeUnit;

/**
 * @className RedisCacheStorager
 * @since JDK 1.6
 */
public class RedisCacheStorager<T extends Cacheable> implements CacheStorager<T> {
    private RedisCache accessTokenRedisCache;

    private ObjectRedisSerializer serializer;

    public RedisCacheStorager(RedisCache accessTokenRedisCache) {
        this.accessTokenRedisCache = accessTokenRedisCache;
        this.serializer = new ObjectRedisSerializer();
    }

    @Override
    public T lookup(String key) {
        T t = null;
        byte[] cacheObject = (byte[]) accessTokenRedisCache.getCacheObject(key);
        if (!ObjectUtils.isEmpty(cacheObject)){
            t = (T) serializer.deserialize(cacheObject);
        }
        return t ;
    }

    @Override
    public void caching(String key, T cache) {
        accessTokenRedisCache.setCacheObject(key, serializer.serialize(cache),(int) (cache.getExpires() - CUTMS) / 1000, TimeUnit.SECONDS);
    }

    @Override
    public T evict(String key) {
        T cache =  (T) accessTokenRedisCache.getCacheObject(key);
        accessTokenRedisCache.deleteObject(key);
        return cache;
    }

    @Override
    public void clear() {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(ALLKEY).append("*");
        Collection<String> keys = accessTokenRedisCache.keys(stringBuffer.toString());
        for (String key : keys) {
            accessTokenRedisCache.deleteObject(key);
        }
    }
}
